package cn.edu.neusoft.wuguangsheng.flowerimpression.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.edu.neusoft.wuguangsheng.flowerimpression.R;
import cn.edu.neusoft.wuguangsheng.flowerimpression.Utils.FullyGridLayoutManager;
import cn.edu.neusoft.wuguangsheng.flowerimpression.adapter.GridImageAdapter;
import cn.edu.neusoft.wuguangsheng.flowerimpression.bean.SuccessBean;
import cn.edu.neusoft.wuguangsheng.flowerimpression.listener.TListener;
import cn.edu.neusoft.wuguangsheng.flowerimpression.model.AddSheQuInfoModel;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class AddSheQuActivity extends BaseActivity {

    private int maxSelectNum = 9;
    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;
    private RecyclerView recycler;
    private PopupWindow pop;
    TextView tv_release,addshequ_cancel;
    EditText tv_point_intro;
    String content;

    LinearLayout addshequ_szwz;
    TextView addshequ_address;

    private Dialog mDialog;

//    private File[] imageFile;
    private File imageFiles;
    private String addressinfo = null;
    //private File imageFiles1;
    //图片列表
    List<String> list_pic = new ArrayList();
    HashMap<String, RequestBody> map = new HashMap<>();


    @Override
    void initView() {
        setLayout_file(R.layout.activity_add_she_qu);
        recycler = (RecyclerView)findViewById(R.id.recycler);
        tv_release = (TextView)findViewById(R.id.tv_release);
        tv_point_intro = (EditText)findViewById(R.id.tv_point_intro);
        addshequ_szwz = (LinearLayout)findViewById(R.id.addshequ_szwz);
        addshequ_address = (TextView)findViewById(R.id.addshequ_address);
        addshequ_cancel = (TextView)findViewById(R.id.addshequ_cancel);
        initWidget();
    }

    @Override
    void initEvent() {
        addshequ_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_release.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 content = tv_point_intro.getText().toString().trim();
                if (content.equals("")){
                    Toast.makeText(AddSheQuActivity.this,"输入内容不能为空",Toast.LENGTH_SHORT).show();
                }
                else {
                    mDialog = WeiboDialogUtils.createLoadingDialog(AddSheQuActivity.this, "发布中...");
                    int i =  list_pic.size();
                    List<String> listfilename = new ArrayList<String>();
                    Log.e("Tag","list1"+list_pic);
                    for (int j = 0;j<i;j++){
                        String path = list_pic.get(j);
                        Log.e("Tag","list1"+list_pic.get(j));
                        imageFiles = new File(path);
                        String name = "images"  + imageFiles.getName();
                        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), imageFiles);
                        //uploadUtilNum.upload(path);
                        Log.e("Tag","name"+name);
//                        map.put(name, requestBody);
                        map.put( "images[]\"; filename=\"" + imageFiles.getName(), requestBody);
//                    File ff = new File(path);
//                    String fname =  ff.getName();
//                    listfilename.add(fname);
                    }
                    Log.e("Tag","map"+""+map.toString());
                    if (map.isEmpty() ){
                        Log.e("Tag","hhh"+""+1);
//                        RequestBody requestBody1 = RequestBody.create(MediaType.parse("multipart/form-data"), imageFiles1);
//                       map.put("images[]\"; filename=\"",requestBody1);

                        if (addressinfo == null){
                            addressinfo="";
                        }

                        AddSheQuInfoModel addSheQuInfoModel = new AddSheQuInfoModel();
                        addSheQuInfoModel.addSheQuMessage(getid(), content,addressinfo, new TListener<SuccessBean>() {
                            @Override
                            public void onResponse(SuccessBean successBean) {
                                if (successBean.getSuccess().equals("1")){
                                    Toast.makeText(AddSheQuActivity.this,"发布成功",Toast.LENGTH_SHORT).show();
                                    DialogThridUtils.closeDialog(mDialog);
                                    finish();

                                }
                                else {
                                    Toast.makeText(AddSheQuActivity.this,"发布失败",Toast.LENGTH_SHORT).show();
                                    DialogThridUtils.closeDialog(mDialog);
                                }
                            }

                            @Override
                            public void onFail(String msg) {
                                Toast.makeText(AddSheQuActivity.this,"发布失败",Toast.LENGTH_SHORT).show();
                                DialogThridUtils.closeDialog(mDialog);
                            }
                        });

                    }
                    else {
                        Log.e("Tag","hhh"+""+2);
                        upload();
                    }
                    //MultipartBody.Part part = MultipartBody.Part.createFormData("image",map,requestBody);

                }

            }
        });

        addshequ_szwz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intenta = new Intent(AddSheQuActivity.this,SheQuAddressActivity.class);
                startActivityForResult(intenta,10);
            }
        });


    }
//    @Override
//    private void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        switch (requestCode){
//            case 1:
//                if(resultCode == RESULT_OK){
//                    String phone = data.getStringExtra("phone");
//                    addshequ_address.setText(phone);
//                    break;
//                }
//            case 2:
//
//        }
//
//    }
    private void upload(){
//        if (imageFile != null){
           // RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"),imageFile);
           // MultipartBody.Part part = MultipartBody.Part.createFormData("image",imageFile.getName(),body);

         //   RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"),imageFile);
            // SetUserHandPhotoModel setUserHandPhotoModel = new SetUserHandPhotoModel();
            //  setUserHandPhotoModel.setUserHandPhoto(part,userid,successBeanTListenerp);
        if (addressinfo == null){
            addressinfo = "";
        }

            AddSheQuInfoModel addSheQuInfoModel=new AddSheQuInfoModel();
            addSheQuInfoModel.addSheQuInfo(map, getid(), content,addressinfo, new TListener<SuccessBean>() {
                @Override
                public void onResponse(SuccessBean successBean) {
                    if (successBean.getSuccess().equals("1")){
                        Toast.makeText(AddSheQuActivity.this,"发布成功",Toast.LENGTH_SHORT).show();
                        DialogThridUtils.closeDialog(mDialog);
                        finish();
                    }
                    else if (successBean.getSuccess().equals("2")){
                        Toast.makeText(AddSheQuActivity.this,"发布失败，上传图片大小单张不可超过1M！",Toast.LENGTH_SHORT).show();
                        DialogThridUtils.closeDialog(mDialog);
                        finish();
                    }
                    else {
                        Toast.makeText(AddSheQuActivity.this,"11",Toast.LENGTH_SHORT).show();
                        DialogThridUtils.closeDialog(mDialog);
                    }
                }

                @Override
                public void onFail(String msg) {
                    Toast.makeText(AddSheQuActivity.this,"1",Toast.LENGTH_SHORT).show();
                    DialogThridUtils.closeDialog(mDialog);
                    Log.e("Tag","msg"+msg);
                }
            });
//        }
    }

//    private String getImagePath(Uri uri, String selection) {
//        String path =null;
//        Cursor cursor =getActivity().getContentResolver().query(uri,
//                null,selection,null,null);
//        if(cursor != null){
//            if(cursor.moveToFirst()){
//                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
//            }
//            cursor.close();
//        }
//        imageFile = new File(path);
//        return path;
//    }



    @Override
    void initDate() {

    }


    private void initWidget() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        recycler.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(AddSheQuActivity.this).externalPicturePreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(AddSheQuActivity.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            PictureSelector.create(AddSheQuActivity.this).externalPictureAudio(media.getPath());
                            break;
                    }
                }
            }
        });
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {

        @Override
        public void onAddPicClick() {
            //第一种方式，弹出选择和拍照的dialog
            showPop();
        }
    };

    private void showPop() {
        View bottomView = View.inflate(AddSheQuActivity.this, R.layout.layout_bottom_dialog, null);
        TextView mAlbum = (TextView) bottomView.findViewById(R.id.tv_album);
        TextView mCamera = (TextView) bottomView.findViewById(R.id.tv_camera);
        TextView mCancel = (TextView) bottomView.findViewById(R.id.tv_cancel);

        pop = new PopupWindow(bottomView, -1, -2);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        pop.setAnimationStyle(R.style.main_menu_photo_anim);
        pop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.tv_album:
                        //相册
                        PictureSelector.create(AddSheQuActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .maxSelectNum(maxSelectNum)
                                .minSelectNum(1)
                                .imageSpanCount(4)
                                .selectionMode(PictureConfig.MULTIPLE)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case R.id.tv_camera:
                        //拍照
                        PictureSelector.create(AddSheQuActivity.this)
                                .openCamera(PictureMimeType.ofImage())
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case R.id.tv_cancel:
                        //取消
                        //closePopupWindow();
                        break;
                }
                closePopupWindow();
            }
        };

        mAlbum.setOnClickListener(clickListener);
        mCamera.setOnClickListener(clickListener);
        mCancel.setOnClickListener(clickListener);
    }
    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    images = PictureSelector.obtainMultipleResult(data);
                    selectList.addAll(images);
                    Log.e("Tag","图片列表"+images);
//                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的

                    list_pic =  adapter.getList1();
                   // Log.e("Tag","图片列表"+list_pic);
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
                case 10:
                    if(resultCode == RESULT_OK){
                         addressinfo = data.getStringExtra("addressinfo");
                        addshequ_address.setText(addressinfo);
                        break;
                    }
            }
        }



    }


}
